import rgeViews, rgeSave
from PyQt4 import QtGui, QtCore, phonon
from rgeSystem import signal, findFiles, LAYER_DIR, POG_DIR, PORTRAIT_DIR, LOG_DIR, IMAGE_EXTENSIONS, CHAR_DIR, MUSIC_DIR, SAVE_DIR, makePortableFilename, promptSaveFile
from rgeJson import loadObject, loadString, jsondump, jsonload
import os, os.path, time
from rgeExtra import *
import rgeSprite
import rgeActor
import rgeModule
import rgeTileset
import rgeScene
import rgeScript

GENERIC_TAB = "GenericTab"
LAYERS_ENABLED_TAB = "LayersEnabled"
MAP_EDITOR_TAB = "MapEditor"
SCENE_GENERAL_TAB = "SceneGeneral"
TILESET_TAB = "TilesetTab"
NOTHING_TAB = "NothingTab"
MODULE_GENERAL_TAB = "ModuleGeneral"
SPRITE_GENERAL_TAB = "SpriteGeneral"
SPRITE_SETTINGS_TAB = "SpriteSettings"
SPRITE_ANIMATION_TAB = "SpriteAnimation"
ACTOR_GENERAL_TAB = "ActorGeneral"
ACTOR_SPRITES_TAB = "ActorSprites"
EXTRAS_TAB = "Extras"


class genericTab(QtGui.QWidget):
    def __init__(self, mainWindow):
        super(QtGui.QWidget, self).__init__(mainWindow)
        self.widgetName = GENERIC_TAB
        self.widgetTitle = "Nothing"
        self.setToolTip(self.tr("Nothing loaded, bub."))
        self.setWindowTitle(self.tr("Nothing!"))
        self.mainLayout = QtGui.QGridLayout()

        self.setLayout(self.mainLayout)


        self.itemOccupied = {}


    def addItem(self, NewItem, PosY, PosX):
        self.mainLayout.addWidget(NewItem, PosY, PosX)
        NewItem.show()
        self.itemOccupied[PosY] = True


    def addItemSpan(self, NewItem, PosY, PosX, EndY, EndX):
        self.mainLayout.addWidget(NewItem, PosY, PosX, EndY, EndX)
        NewItem.show()
        for i in range(EndY - PosY):
            self.itemOccupied[i + PosY] = True


    def appendItem(self, NewItem):
        i = 0
        while i in self.itemOccupied:
            i = i +1
        self.addItem(NewItem.getLabel(), i, 0)
        self.addItem(NewItem.getEditor(), i, 1)
        self.addItem(NewItem.getUnchanged(), i, 2)
        self.itemOccupied[i] = True



class layerItem(QtGui.QListWidgetItem):

    def __init__(self, text, layer, enabled = True):
        QtGui.QListWidgetItem.__init__(self, text)
        self.layer = layer
        self.enabled = enabled

    def enable(self):
        self.setText("Layer: " + str(self.layer) + " [enabled]")
        self.enabled = True

    def disable(self):
        self.setText("Layer: " + str(self.layer) + " [disabled]")
        self.enabled = False

    def toggle(self):
        if self.enabled:
            self.disable()
        else:
            self.enable()

class nothingLoadedPalette(genericTab):
    """Just shows nothing's loaded'"""

    def __init__(self, mainWindow, TabTypeName):
        """Initializes."""
        super(nothingLoadedPalette, self).__init__(mainWindow)
        self.widgetName = NOTHING_TAB
        self.widgetTitle = "Nothing"
        self.setToolTip(self.tr("Nothing loaded, bub."))
        self.setWindowTitle(self.tr("Nothing!"))

        self.textMessage = QtGui.QLabel("No " + TabTypeName + " loaded.")
        self.newButton = QtGui.QPushButton("New " + TabTypeName)
        self.loadButton = QtGui.QPushButton("Load " + TabTypeName)


        self.newButton.clicked.connect(rgeViews.newSomething)
        self.loadButton.clicked.connect(rgeViews.loadSomething)

        self.addItem(self.textMessage,0,0)
        self.addItem(self.textMessage,0,0)
        self.addItem(self.newButton,1,0)
        self.addItem(self.loadButton,1,1)


class extrasWidget:
    def __init__(self, Layout = QtGui.QGridLayout()):
        self.layout = Layout
        self.itemOccupied = {}


    def appendItem(self, NewItem):
        i = 0
        while i in self.itemOccupied:
            i = i +1
        self.addItem(NewItem.getLabel(), i, 0)
        self.addItem(NewItem.getEditor(), i, 1)
        self.addItem(NewItem.getUnchanged(), i, 2)
        self.itemOccupied[i] = True


    def getLayout(self):
        return self.layout



class extrasPalette(genericTab):
    def __init__(self, mainWindow, Settings):
        super(extrasPalette, self).__init__(mainWindow)
        self.widgetName = EXTRAS_TAB
        self.widgetTitle = "Extras"
        self.setToolTip(self.tr(""))
        self.setWindowTitle(self.tr("Extras"))

        self.intLayout = extrasWidget()
        self.addInt = QtGui.QPushButton("Add Int")
        self.floatLayout = extrasWidget()
        self.addFloat = QtGui.QPushButton("Add Float")
        self.boolLayout = extrasWidget()
        self.addBool = QtGui.QPushButton("Add Bool")
        self.stringLayout = extrasWidget()
        self.addString = QtGui.QPushButton("Add String")

        self.addInt.clicked.connect(rgeViews.addExtraInt)
        self.addFloat.clicked.connect(rgeViews.addExtraFloat)
        self.addBool.clicked.connect(rgeViews.addExtraBool)
        self.addString.clicked.connect(rgeViews.addExtraString)

        self.addItemSpan(self.intLayout.getLayout(), 0, 0, 1, 1)
        self.addItem(self.addInt,2,0)
        self.addItemSpan(self.floatLayout.getLayout(), 3, 0, 4, 1)
        self.addItem(self.addFloat,5,0)
        self.addItemSpan(self.boolLayout.getLayout(), 6, 0, 7, 1)
        self.addItem(self.addBool,8,0)
        self.addItemSpan(self.stringLayout.getLayout(), 9, 0, 10, 1)
        self.addItem(self.addString,11,0)

        for x in Settings.Data:
            self.appendItemExtra(x)


    def appendItemExtra(self, NewItem):
        if type(NewItem) is IntItem:
            self.intLayout.appendItem(NewItem)
        elif type(NewItem) is FloatItem:
            self.floatLayout.appendItem(NewItem)
        elif type(NewItem) is BoolItem:
            self.boolLayout.appendItem(NewItem)
        elif type(NewItem) is StringItem:
            self.stringLayout.appendItem(NewItem)

class layerEnabledPalette(QtGui.QWidget):
    """Widget that toggles layer display in the editor"""

    layersChanged = QtCore.pyqtSignal(list)

    def __init__(self, mainWindow, Settings):
        """Initializes."""
        super(QtGui.QWidget, self).__init__(mainWindow)
        self.widgetName = LAYERS_ENABLED_TAB
        self.widgetTitle = "Layers"
        self.setToolTip(self.tr("Determines which layers are displayed in the editor."))
        self.setWindowTitle(self.tr("Enabled Layers"))
        self.mainLayout = QtGui.QGridLayout()
        self.checkAllLayersButton = QtGui.QPushButton("Check All Layers")
        self.uncheckAllLayersButton = QtGui.QPushButton("Uncheck All Layers")
        self.toggleLayerButton = QtGui.QPushButton("Toggle Enable/Disable")
        self.checkAllLayersButton.clicked.connect(self.allPressed)
        self.uncheckAllLayersButton.clicked.connect(self.allUnPressed)
        self.toggleLayerButton.clicked.connect(self.togglePressed)

        self.layersChanged.connect(rgeViews.toggleLayerVisibility)

        self.layerList = QtGui.QListWidget()
        self.layerList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        for i in range(Settings.getNumOfLayers()):
            self.layerList.addItem(layerItem("Layer: " + str(i) + " [enabled]", i))

        self.mainLayout.addWidget(self.checkAllLayersButton,0,0)
        self.mainLayout.addWidget(self.uncheckAllLayersButton,0,1)
        self.mainLayout.addWidget(self.layerList,1,0)
        self.mainLayout.addWidget(self.toggleLayerButton,1,1)
        self.setLayout(self.mainLayout)
        self.setObjectName("Enabled Layers")

    def allPressed(self, checked):
        layers = []

        for i in range(self.layerList.count()):
            item = self.layerList.item(i)

            if not item.enabled:
                item.enable()
                layers.append(item.layer)

        self.layersChanged.emit(layers)

    def allUnPressed(self, checked):
        layers = []

        for i in range(self.layerList.count()):
            item = self.layerList.item(i)

            if item.enabled:
                item.disable()
                layers.append(item.layer)

        self.layersChanged.emit(layers)

    def togglePressed(self, checked):
        tempitems = self.layerList.selectedItems() #returns a QList of layerItem, see above
        layers = []

        for item in tempitems:
            layers.append(item.layer)
            item.toggle()

        self.layersChanged.emit(layers)

    def setLayers(self, newAmount):
        offset = self.layerList.count()
        for i in range(newAmount - self.layerList.count()):
            self.layerList.addItem(layerItem("Layer: " + str(i+offset) + " [enabled]", i+offset))
        for i in range(self.layerList.count() - newAmount):
            self.layerList.takeItem(offset-i-1)


class tilesetSettingsPalette(genericTab):
    """tileset settings widget"""

    LabelPrefix = "Map Name (editor only):"

    def __init__(self, mainWindow, TilesetSettings = rgeTileset.TilesetData()):
        """Init"""
        super(tilesetSettingsPalette, self).__init__(mainWindow)
        self.widgetName = TILESET_TAB
        self.widgetTitle = "Tileset"
        self.setToolTip(self.tr("Messes with tileset settings."))
        self.setWindowTitle(self.tr("Tileset"))

        self.name = TilesetSettings.name

        self.nameLabel = QtGui.QLabel(self.LabelPrefix)
        self.nameLabelActual = QtGui.QLabel(self.name)
        self.nameBox = QtGui.QLineEdit(self.name)
        self.layerTileSizeXLabel = QtGui.QLabel("Tile X width:")
        self.layerTileSizeYLabel = QtGui.QLabel("Tile Y width:")
        self.layerTileSizeX = QtGui.QLabel(str(TilesetSettings.getWidth()))
        self.layerTileSizeY = QtGui.QLabel(str(TilesetSettings.getHeight()))
        self.layerTileSizeXButton = QtGui.QPushButton("Change")
        self.layerTileSizeYButton = QtGui.QPushButton("Change")
        self.layerTileNumberXLabel = QtGui.QLabel("Number of Tiles, X:")
        self.layerTileNumberYLabel = QtGui.QLabel("Number of Tiles, Y:")
        self.layerTileNumberX = QtGui.QLabel(str(TilesetSettings.getTileNumX()))
        self.layerTileNumberY = QtGui.QLabel(str(TilesetSettings.getTileNumY()))
        self.layerTileNumberXButton = QtGui.QPushButton("Change")
        self.layerTileNumberYButton = QtGui.QPushButton("Change")
        self.saveButton = QtGui.QPushButton("Save")
        self.loadButton = QtGui.QPushButton("Load")
        self.newButton = QtGui.QPushButton("New Tileset")
        self.changeButton = QtGui.QPushButton("Change Image")


        self.saveButton.pressed.connect(rgeViews.saveCurrentTileset)
        self.loadButton.pressed.connect(rgeViews.openTileset)
        self.newButton.pressed.connect(rgeViews.newTileset)
        self.changeButton.pressed.connect(rgeViews.changeTilesetImage)
        self.nameBox.returnPressed.connect(self.nameChanged)
        self.layerTileSizeXButton.clicked.connect(rgeViews.tilesetTileSizeX)
        self.layerTileSizeYButton.clicked.connect(rgeViews.tilesetTileSizeY)
        self.layerTileNumberXButton.clicked.connect(rgeViews.tilesetTileNumberX)
        self.layerTileNumberYButton.clicked.connect(rgeViews.tilesetTileNumberY)

        self.addItem(self.nameLabel,0,0)
        self.addItem(self.nameLabelActual,0,1)
        self.addItem(self.nameBox,1,1)
        self.addItem(self.saveButton,2,0)
        self.addItem(self.loadButton,2,1)
        self.addItem(self.newButton,3,0)
        self.addItem(self.changeButton,3,1)
        self.addItem(self.layerTileSizeXLabel,6,0)
        self.addItem(self.layerTileSizeYLabel,6,1)
        self.addItem(self.layerTileSizeX,7,0)
        self.addItem(self.layerTileSizeY,7,1)
        self.addItem(self.layerTileSizeXButton,8,0)
        self.addItem(self.layerTileSizeYButton,8,1)
        self.addItem(self.layerTileNumberXLabel,9,0)
        self.addItem(self.layerTileNumberYLabel,9,1)
        self.addItem(self.layerTileNumberX,10,0)
        self.addItem(self.layerTileNumberY,10,1)
        self.addItem(self.layerTileNumberXButton,11,0)
        self.addItem(self.layerTileNumberYButton,11,1)


    def updateBoxValues(self, TilesetSettings):
        self.layerTileSizeX.setText(str(TilesetSettings.getWidth()))
        self.layerTileSizeY.setText(str(TilesetSettings.getHeight()))
        self.layerTileNumberX.setText(str(TilesetSettings.getTileNumX()))
        self.layerTileNumberY.setText(str(TilesetSettings.getTileNumY()))

    def nameChanged(self):
        self.name = self.nameBox.text()
        self.nameLabelActual.setText(self.name)
        rgeViews.setTilesetName(self.name)


class layerSetValuesPalette(genericTab):
    """Widget that sets all the values associated with layers"""

    def __init__(self, mainWindow, Settings, currentLayer):
        """Init"""
        super(layerSetValuesPalette, self).__init__(mainWindow)
        self.widgetName = MAP_EDITOR_TAB
        self.widgetTitle = "Map"
        self.setToolTip(self.tr("Determines which layers are displayed in the editor."))
        self.setWindowTitle(self.tr("Enabled Layers"))

        TempX = 1
        TempY = 1
        if len(Settings.getLayer(currentLayer)) > 0:
            TempX = Settings.getWidth(currentLayer)
            TempY = Settings.getHeight(currentLayer)
        self.mapSize = [TempX,TempY]

        self.layerActiveLabel = QtGui.QLabel("Currently Active Layer:")
        self.layerActiveBox = QtGui.QSpinBox()
        self.layerActiveBox.setRange(0,Settings.getNumOfLayers() - 1)
        self.layerActiveBox.setValue(currentLayer)
        self.layerAmountLabel = QtGui.QLabel("Number of Layers:")
        self.layerAmountBox = QtGui.QSpinBox()
        self.layerAmountBox.setRange(20,100)
        self.setLayerAmount(Settings.getNumOfLayers())
        self.layerLoadImage = QtGui.QPushButton("Load New Tileset")
        self.layerRemoveImage = QtGui.QPushButton("Remove Tileset")
        self.layerTilemapSizeXLabel = QtGui.QLabel("Map X width:")
        self.layerTilemapSizeYLabel = QtGui.QLabel("Map Y height:")
        self.layerTilemapSizeX = QtGui.QLabel(QtCore.QString(str(Settings.getWidth(currentLayer))))
        self.layerTilemapSizeY = QtGui.QLabel(QtCore.QString(str(Settings.getHeight(currentLayer))))
        self.layerSizeButtonX = QtGui.QPushButton("Set Width")
        self.layerSizeButtonY = QtGui.QPushButton("Set Height")
        self.mapSizeLabel = QtGui.QLabel("Map Size:")
        self.mapSizeLabelActual = QtGui.QLabel("")

        rgeViews.setNumberOfLayers(Settings.getNumOfLayers())
        self.updateSize()

        self.layerSizeButtonX.clicked.connect(rgeViews.sceneSetXButton)
        self.layerSizeButtonY.clicked.connect(rgeViews.sceneSetYButton)
        self.layerAmountBox.valueChanged.connect(rgeViews.sceneSetNumOfLayers)
        self.layerActiveBox.valueChanged.connect(rgeViews.sceneSetCurrentLayer)
        self.layerLoadImage.clicked.connect(rgeViews.chooseTilemap)
        self.layerRemoveImage.clicked.connect(rgeViews.sceneCloseMap)

        self.addItem(self.layerAmountLabel,0,0)
        self.addItem(self.layerAmountBox,0,1)
        self.addItem(self.layerActiveLabel,1,0)
        self.addItem(self.layerActiveBox,1,1)
        self.addItem(self.layerLoadImage,2,0)
        self.addItem(self.layerRemoveImage,2,1)
        self.addItem(self.layerTilemapSizeXLabel,4,0)
        self.addItem(self.layerTilemapSizeYLabel,4,1)
        self.addItem(self.layerTilemapSizeX,5,0)
        self.addItem(self.layerTilemapSizeY,5,1)
        self.addItem(self.layerSizeButtonX,6,0)
        self.addItem(self.layerSizeButtonY,6,1)
        self.addItem(self.mapSizeLabel,7,0)
        self.addItem(self.mapSizeLabelActual,7,1)




    def setLayerAmount(self, NewAmount):
        self.layerActiveBox.setRange(0,NewAmount-1)
        self.layerAmountBox.setValue(NewAmount)

    def updateBoxValues(self, Settings, currentLayer):
        self.layerTilemapSizeX.setText(str(Settings.getWidth(currentLayer)))
        self.layerTilemapSizeY.setText(str(Settings.getHeight(currentLayer)))
        Tileset = rgeTileset.TilesetData()
        Tileset.loadFromFile(Settings.getLayer(currentLayer))
        self.setSize(Tileset.getWidth(), Tileset.getHeight())


    def setSize(self,NewX, NewY):
        self.mapSize = [NewX, NewY]
        self.updateSize()

    def updateSize(self):
        self.mapSizeLabelActual.setText(str(self.layerTilemapSizeX.text().toInt()[0] * self.mapSize[0]) + 'x' + str(self.layerTilemapSizeY.text().toInt()[0] * self.mapSize[1]))


class moduleGeneralSettingsPalette(genericTab):
    ''' general settings for this'''

    def __init__(self, mainWindow, Settings = rgeModule.ModuleData()):
        super(moduleGeneralSettingsPalette, self).__init__(mainWindow)
        self.widgetName = MODULE_GENERAL_TAB
        self.widgetTitle = "General"
        self.setToolTip(self.tr("General settings for module."))
        self.setWindowTitle(self.tr("General Settings"))

        self.name = Settings.name

        self.nameLabel = QtGui.QLabel("Module Name:")
        self.nameBox = QtGui.QLineEdit(self.name)
        self.nameBox.returnPressed.connect(self.nameChanged)
        self.startingSceneLabel = QtGui.QLabel("Starting Scene:")
        if Settings.getStartingScene() == None:
            self.startingSceneName = QtGui.QLabel("")
        else:
            self.startingSceneName = QtGui.QLabel(rgeSave.getName(Settings.getStartingScene()))
        self.scriptPythonLabel = QtGui.QLabel("Python Script: ")
        if Settings.getPythonScript() == None:
            self.scriptPythonName = QtGui.QLabel("")
        else:
            self.scriptPythonName = QtGui.QLabel(Settings.getPythonScript())
        self.chooseStartingSceneButton = QtGui.QPushButton("Choose Scene")
        self.chooseStartingSceneButton.clicked.connect(self.startingSceneChange)
        self.choosePythonScript = QtGui.QPushButton("Choose Python Script")
        self.choosePythonScript.clicked.connect(self.scriptPythonChange)
        self.saveModButton = QtGui.QPushButton("Save Mod")
        self.loadModButton = QtGui.QPushButton("Load Mod")
        self.newModButton = QtGui.QPushButton("New Mod")
        self.saveModButton.clicked.connect(rgeViews.saveCurrentMod)
        self.loadModButton.clicked.connect(rgeViews.openModule)
        self.newModButton.clicked.connect(rgeViews.newModule)

        self.addItem(self.nameLabel,0,0)
        self.addItem(self.nameBox,0,1)
        self.addItem(self.startingSceneLabel,1,0)
        self.addItem(self.startingSceneName,1,1)
        self.addItem(self.chooseStartingSceneButton,2,1)
        self.addItem(self.scriptPythonLabel,3,0)
        self.addItem(self.scriptPythonName,3,1)
        self.addItem(self.choosePythonScript,4,1)
        self.addItem(self.saveModButton,5,0)
        self.addItem(self.loadModButton,5,1)
        self.addItem(self.newModButton,6,0)


    def nameChanged(self):
        self.name = self.nameBox.text()
        rgeViews.setModuleName(self.nameBox.text())

    def startingSceneChange(self):
        ScenePath = rgeViews.chooseScene()
        if ScenePath != None:
            rgeViews.modSetStartingScene(ScenePath.selectedFile)
            self.startingSceneName.setText(rgeSave.getName(ScenePath.selectedFile))

    def scriptPythonChange(self):
        ScriptPath = rgeViews.choosePythonScript()
        if ScriptPath:
            NewLoc = rgeViews.modSetPythonScript(ScriptPath)
            if NewLoc:
                self.scriptPythonName.setText(NewLoc)


class sceneGeneralSettingsTab(genericTab):
    ''' general settings for this'''

    def __init__(self, mainWindow, Settings):
        super(sceneGeneralSettingsTab, self).__init__(mainWindow)
        self.widgetName = SCENE_GENERAL_TAB
        self.widgetTitle = "General"
        self.setToolTip(self.tr("General settings for scenes."))
        self.setWindowTitle(self.tr("General Settings"))

        self.nameLabel = QtGui.QLabel("Scene Name (editor only):")
        self.nameDisplay = QtGui.QLabel(Settings.name)
        self.nameBox = QtGui.QLineEdit(Settings.name)
        self.nameBox.returnPressed.connect(self.nameChanged)
        self.saveButton = QtGui.QPushButton("Save Scene")
        self.loadButton = QtGui.QPushButton("Load Scene")
        self.newButton = QtGui.QPushButton("New Scene")

        self.saveButton.clicked.connect(rgeViews.saveCurrentScene)
        self.loadButton.clicked.connect(rgeViews.openScene)
        self.newButton.clicked.connect(rgeViews.newScene)

        self.addItem(self.nameLabel,0,0)
        self.addItem(self.nameDisplay,0,1)
        self.addItem(self.nameBox,1,1)
        self.addItem(self.saveButton,2,0)
        self.addItem(self.loadButton,2,1)
        self.addItem(self.newButton,3,0)


    def nameChanged(self):
        self.nameDisplay.setText(self.nameBox.text())
        rgeViews.setSceneName(self.nameBox.text())


class spriteGeneralSettingsTab(genericTab):
    ''' general settings for this'''

    def __init__(self, mainWindow, Settings):
        super(spriteGeneralSettingsTab, self).__init__(mainWindow)
        self.widgetName = SPRITE_GENERAL_TAB
        self.widgetTitle = "General"
        self.setToolTip(self.tr("General settings for sprites."))
        self.setWindowTitle(self.tr("General Settings"))

        self.nameLabel = QtGui.QLabel("Sprite Name (editor only):")
        self.nameDisplay = QtGui.QLabel(Settings.name)
        self.nameBox = QtGui.QLineEdit(Settings.name)
        self.nameBox.returnPressed.connect(self.nameChanged)
        self.saveButton = QtGui.QPushButton("Save Sprite")
        self.loadButton = QtGui.QPushButton("Load Sprite")
        self.newButton = QtGui.QPushButton("New Sprite")

        self.saveButton.clicked.connect(rgeViews.saveCurrentSprite)
        self.loadButton.clicked.connect(rgeViews.openSprite)
        self.newButton.clicked.connect(rgeViews.newSprite)

        self.addItem(self.nameLabel,0,0)
        self.addItem(self.nameDisplay,0,1)
        self.addItem(self.nameBox,1,1)
        self.addItem(self.saveButton,2,0)
        self.addItem(self.loadButton,2,1)
        self.addItem(self.newButton,3,0)


    def nameChanged(self):
        self.nameDisplay.setText(self.nameBox.text())
        rgeViews.setSpriteName(self.nameBox.text())


class spriteSettingsPalette(genericTab):
    """Widget that sets all the values associated with layers"""

    def __init__(self, mainWindow, Settings, currentLayer):
        """Init"""
        super(spriteSettingsPalette, self).__init__(mainWindow)
        self.widgetName = SPRITE_SETTINGS_TAB
        self.widgetTitle = "Textures"
        self.setToolTip(self.tr("General settings for sprites."))
        self.setWindowTitle(self.tr("General Settings"))

        self.textureList = QtGui.QComboBox()
        self.newTextureButton = QtGui.QPushButton("New Texture")
        self.removeTextureButton = QtGui.QPushButton("Remove Texture")
        self.nameLabel = QtGui.QLabel("Name:")
        if Settings.getTextureLength() > currentLayer:
            self.nameName = QtGui.QLineEdit(Settings.getTextureName(currentLayer))
        else:
            self.nameName = QtGui.QLineEdit()
        self.splitXLabel = QtGui.QLabel("Number of Frames (x):")
        self.splitYLabel = QtGui.QLabel("Number of Frames (y):")

        if Settings.getTextureLength() > currentLayer and currentLayer >= 0:
            Split = Settings.getTextureSplit(currentLayer)
            self.splitXNum = QtGui.QLabel(str(Split[0]))
            self.splitYNum = QtGui.QLabel(str(Split[1]))
        else:
            self.splitXNum = QtGui.QLabel()
            self.splitYNum = QtGui.QLabel()
        self.splitXButton = QtGui.QPushButton("Change")
        self.splitYButton = QtGui.QPushButton("Change")

        self.connectList()
        self.newTextureButton.clicked.connect(rgeViews.spriteNewTexture)
        self.removeTextureButton.clicked.connect(rgeViews.spriteRemoveTexture)
        self.splitXButton.clicked.connect(rgeViews.spriteSplitTextureX)
        self.splitYButton.clicked.connect(rgeViews.spriteSplitTextureY)
        self.nameName.returnPressed.connect(self.nameChanged)

        self.updateTextures(Settings, currentLayer)

        self.addItem(self.textureList,0,0)
        self.addItem(self.newTextureButton,1,0)
        self.addItem(self.removeTextureButton,1,1)
        self.addItem(self.nameLabel,2,0)
        self.addItem(self.nameName,2,1)
        self.addItem(self.splitXLabel,3,0)
        self.addItem(self.splitYLabel,3,1)
        self.addItem(self.splitXNum,4,0)
        self.addItem(self.splitYNum,4,1)
        self.addItem(self.splitXButton,5,0)
        self.addItem(self.splitYButton,5,1)

    def connectList(self):
        self.textureList.currentIndexChanged.connect(rgeViews.spriteChangeTexture)

    def unconnectList(self):
        self.textureList.currentIndexChanged.disconnect(rgeViews.spriteChangeTexture)


    def updateSplits(self, Sprite, Layer):
        if Sprite.getAnimationNum() > Layer:
            Split = Sprite.getTextureSplit(Layer)
            self.splitXNum.setText(str(Split[0]))
            self.splitYNum.setText(str(Split[1]))

    def updateTextures(self, Sprite, currentLayer):
        self.unconnectList()
        self.textureList.clear()
        if currentLayer >= 0:
            if Sprite.getTextureLength() > currentLayer:
                NamesList = Sprite.getAllTexNames()
                for x in NamesList:
                    self.textureList.addItem(x)
                self.textureList.setCurrentIndex(currentLayer)
                self.nameName.setText(NamesList[currentLayer])
        self.connectList()
        self.updateSplits(Sprite, currentLayer)

    def nameChanged(self):
        rgeViews.setSpriteTextureName(self.nameName.text())


class spriteAnimationPalette(genericTab):
    """Widget that sets all the values associated with animation"""

    def __init__(self, mainWindow, Settings, spriteAnimation = 0, spriteFrame = 0):
        """Init"""
        super(spriteAnimationPalette, self).__init__(mainWindow)
        self.widgetName = SPRITE_ANIMATION_TAB
        self.widgetTitle = "Animation"
        self.setToolTip(self.tr("Animation settings for sprites."))
        self.setWindowTitle(self.tr("Animation Settings"))

        self.animationDropdown = QtGui.QComboBox()
        self.animationName = QtGui.QLineEdit()
        self.aniNumLabel = QtGui.QLabel("Number of Anis: ")
        self.aniNum = QtGui.QLabel()
        self.aniNumButton = QtGui.QPushButton("Change")
        self.aniCopyLabel = QtGui.QLabel("Animation Copy: ")
        self.aniCopyLabelNum = QtGui.QLabel("")
        self.animationCopy = QtGui.QPushButton("Copy Ani")
        self.animationPaste = QtGui.QPushButton("Paste Ani")
        self.framesLabel = QtGui.QLabel("Number of frames:")
        self.frames = QtGui.QLabel()
        self.frameNumButton = QtGui.QPushButton("Change")
        self.currentFrameLabel = QtGui.QLabel("Current Frame:")
        self.currentFrame = QtGui.QSpinBox()
        self.copyButton = QtGui.QPushButton("Copy")
        self.texturePickerLabel = QtGui.QLabel("Current Texture:")
        self.texturePicker = QtGui.QComboBox()
        self.tileXLabel = QtGui.QLabel("Tile X")
        self.tileX = QtGui.QSpinBox()
        self.tileYLabel = QtGui.QLabel("Tile Y")
        self.tileY = QtGui.QSpinBox()
        self.offsetXLabel = QtGui.QLabel("Offset X")
        self.OffsetX = QtGui.QSpinBox()
        self.OffsetX.setRange(-10000000,10000000)
        self.offsetYLabel = QtGui.QLabel("Offset Y")
        self.OffsetY = QtGui.QSpinBox()
        self.OffsetY.setRange(-10000000,10000000)
        self.flipXLabel = QtGui.QLabel("Flip X:")
        self.flipX = QtGui.QCheckBox()
        self.flipYLabel = QtGui.QLabel("Flip Y:")
        self.flipY = QtGui.QCheckBox()
        self.sizeXLabel = QtGui.QLabel("Size X:")
        self.sizeX = QtGui.QDoubleSpinBox()
        self.sizeX.setDecimals(4)
        self.sizeX.setRange(.0001,1000)
        self.sizeYLabel = QtGui.QLabel("Size Y:")
        self.sizeY = QtGui.QDoubleSpinBox()
        self.sizeY.setDecimals(4)
        self.sizeY.setRange(.0001,1000)
        self.timeLabel = QtGui.QLabel("Ani Time:")
        self.time = QtGui.QDoubleSpinBox()
        self.time.setDecimals(4)
        self.time.setRange(0.0001,100000)
        self.centerLabel = QtGui.QLabel("Center Size:")
        self.center = QtGui.QCheckBox()
        self.playbutton = QtGui.QPushButton("Play")
        self.pausebutton = QtGui.QPushButton("Pause")

        self.connectStuff()
        self.aniNumButton.clicked.connect(rgeViews.spriteAniNumChanged)
        self.animationCopy.clicked.connect(rgeViews.spriteAnimationCopyAnimation)
        self.animationPaste.clicked.connect(rgeViews.spriteAnimationPasteAnimation)
        self.animationName.returnPressed.connect(self.NameChanged)
        self.frameNumButton.clicked.connect(rgeViews.spriteNumFrameChanged)
        self.copyButton.clicked.connect(rgeViews.spriteAnimationCopyFrame)
        self.playbutton.clicked.connect(rgeViews.playSpriteAnimation)
        self.pausebutton.clicked.connect(rgeViews.pauseSpriteAnimation)

        self.setupBoxes(Settings, spriteFrame, spriteAnimation)


        self.addItem(self.animationDropdown,0,0)
        self.addItem(self.animationName,0,1)
        self.addItem(self.aniCopyLabel,1,0)
        self.addItem(self.aniCopyLabelNum,1,1)
        self.addItem(self.animationCopy,2,0)
        self.addItem(self.animationPaste,2,1)
        self.addItem(self.aniNumLabel,3,0)
        self.addItem(self.aniNum,3,1)
        self.addItem(self.aniNumButton,4,1)
        self.addItem(self.framesLabel,5,0)
        self.addItem(self.frames,5,1)
        self.addItem(self.frameNumButton,6,1)
        self.addItem(self.currentFrameLabel,7,0)
        self.addItem(self.currentFrame,7,1)
        self.addItem(self.texturePickerLabel,8,0)
        self.addItem(self.texturePicker,8,1)
        self.addItem(self.tileXLabel,9,0)
        self.addItem(self.tileX,9,1)
        self.addItem(self.tileYLabel,10,0)
        self.addItem(self.tileY,10,1)
        self.addItem(self.offsetXLabel,11,0)
        self.addItem(self.OffsetX,11,1)
        self.addItem(self.offsetYLabel,12,0)
        self.addItem(self.OffsetY,12,1)
        self.addItem(self.flipXLabel,13,0)
        self.addItem(self.flipX,13,1)
        self.addItem(self.flipYLabel,14,0)
        self.addItem(self.flipY,14,1)
        self.addItem(self.sizeXLabel,15,0)
        self.addItem(self.sizeX,15,1)
        self.addItem(self.sizeYLabel,16,0)
        self.addItem(self.sizeY,16,1)
        self.addItem(self.timeLabel,17,0)
        self.addItem(self.time,17,1)
        self.addItem(self.centerLabel,18,0)
        self.addItem(self.center,18,1)
        self.addItem(self.copyButton,19,0)
        self.addItem(self.copyButton,19,0)
        self.addItem(self.playbutton, 20, 0)
        self.addItem(self.pausebutton, 20, 1)

    def NameChanged(self):
        rgeViews.spriteAnimationNameChanged(self.animationName.text())

    def setupBoxes(self, Settings, spriteFrame = 0, spriteAnimation = 0):
        self.disconnectStuff()
        if spriteFrame == -1:
            spriteFrame = self.currentFrame.value()
        if spriteAnimation == -1:
            spriteAnimation = self.animationDropdown.currentIndex()
        if Settings.getAnimationNum() < spriteAnimation:
            spriteAnimation = Settings.getAnimationNum() - 1
        self.animationDropdown.clear()
        for i in xrange(Settings.getAnimationNum()):
            self.animationDropdown.addItem(str(i) + " - " + Settings.getAnimationName(i))
        self.animationDropdown.setCurrentIndex(spriteAnimation)
        self.animationName.setText(Settings.getAnimationName(spriteAnimation))
        self.aniNum.setText(str(Settings.getAnimationNum()))
        self.aniCopyLabelNum.setText(str(Settings.getCopyNum()) + " - " + Settings.getAnimationName(Settings.getCopyNum()))
        self.frames.setText(str(Settings.getFrameNum(spriteAnimation)))
        if spriteFrame >= Settings.getFrameNum(spriteAnimation):
            spriteFrame = Settings.getFrameNum(spriteAnimation) - 1
        self.currentFrame.setRange(0,Settings.getFrameNum(spriteAnimation) - 1)
        self.currentFrame.setValue(spriteFrame)
        self.texturePicker.clear()
        TexNames = Settings.getAllTexNames()
        for x in TexNames:
            self.texturePicker.addItem(x)
        TexNum = Settings.getTextureNum(spriteAnimation,spriteFrame)
        TexValues = Settings.getTextureValues(spriteAnimation, spriteFrame)
        Split = Settings.getTextureSplit(TexNum)
        Offsets = Settings.getOffset(spriteAnimation, spriteFrame)
        Flips = Settings.getFlip(spriteAnimation, spriteFrame)
        Sizes = Settings.getSize(spriteAnimation, spriteFrame)
        self.texturePicker.setCurrentIndex(TexNum)
        self.tileX.setRange(1,Split[0])
        self.tileY.setRange(1,Split[1])
        self.tileX.setValue(TexValues[0])
        self.tileY.setValue(TexValues[1])
        self.OffsetX.setValue(Offsets[0])
        self.OffsetY.setValue(Offsets[1])
        self.flipX.setChecked(Flips[0])
        self.flipY.setChecked(Flips[1])
        self.sizeX.setValue(Sizes[0])
        self.sizeY.setValue(Sizes[1])
        self.time.setValue(Settings.getTime(spriteAnimation, spriteFrame))
        self.center.setChecked(Settings.getCenter(spriteAnimation, spriteFrame))
        self.connectStuff()

    def connectStuff(self):
        self.animationDropdown.currentIndexChanged.connect(rgeViews.spriteAnimationChanged)
        self.currentFrame.valueChanged.connect(rgeViews.spriteAnimationFrameChanged)
        self.tileX.valueChanged.connect(rgeViews.spriteFrameXChanged)
        self.tileY.valueChanged.connect(rgeViews.spriteFrameYChanged)
        self.OffsetX.valueChanged.connect(rgeViews.spriteOffsetXChanged)
        self.OffsetY.valueChanged.connect(rgeViews.spriteOffsetYChanged)
        self.texturePicker.currentIndexChanged.connect(rgeViews.spriteAnimationTextureChanged)
        self.flipX.toggled.connect(self.flipXSignal)
        self.flipY.toggled.connect(self.flipYSignal)
        self.sizeX.valueChanged.connect(rgeViews.spriteSizeXChanged)
        self.sizeY.valueChanged.connect(rgeViews.spriteSizeYChanged)
        self.time.valueChanged.connect(rgeViews.spriteTimeChanged)
        self.center.toggled.connect(self.centerSignal)

    def disconnectStuff(self):
        self.animationDropdown.currentIndexChanged.disconnect(rgeViews.spriteAnimationChanged)
        self.currentFrame.valueChanged.disconnect(rgeViews.spriteAnimationFrameChanged)
        self.tileX.valueChanged.disconnect(rgeViews.spriteFrameXChanged)
        self.tileY.valueChanged.disconnect(rgeViews.spriteFrameYChanged)
        self.OffsetX.valueChanged.disconnect(rgeViews.spriteOffsetXChanged)
        self.OffsetY.valueChanged.disconnect(rgeViews.spriteOffsetYChanged)
        self.texturePicker.currentIndexChanged.disconnect(rgeViews.spriteAnimationTextureChanged)
        self.flipX.toggled.disconnect(self.flipXSignal)
        self.flipY.toggled.disconnect(self.flipYSignal)
        self.sizeX.valueChanged.disconnect(rgeViews.spriteSizeXChanged)
        self.sizeY.valueChanged.disconnect(rgeViews.spriteSizeYChanged)
        self.time.valueChanged.disconnect(rgeViews.spriteTimeChanged)
        self.center.toggled.disconnect(self.centerSignal)

    def flipXSignal(self):
        rgeViews.spriteFlipXChanged(self.flipX.isChecked())

    def flipYSignal(self):
        rgeViews.spriteFlipYChanged(self.flipY.isChecked())

    def centerSignal(self):
        rgeViews.spriteCenterChanged(self.center.isChecked())


class actorGeneralSettingsTab(genericTab):
    ''' general settings for this'''

    def __init__(self, mainWindow, Settings):
        super(actorGeneralSettingsTab, self).__init__(mainWindow)
        self.widgetName = ACTOR_GENERAL_TAB
        self.widgetTitle = "General"
        self.setToolTip(self.tr("General settings for actors."))
        self.setWindowTitle(self.tr("General Settings"))

        self.nameLabel = QtGui.QLabel("Actor Name (editor only):")
        self.nameDisplay = QtGui.QLabel(Settings.name)
        self.nameBox = QtGui.QLineEdit(Settings.name)
        self.nameBox.returnPressed.connect(self.nameChanged)
        self.saveButton = QtGui.QPushButton("Save Actor")
        self.loadButton = QtGui.QPushButton("Load Actor")
        self.newButton = QtGui.QPushButton("New Actor")

        self.saveButton.clicked.connect(rgeViews.saveCurrentActor)
        self.loadButton.clicked.connect(rgeViews.openActor)
        self.newButton.clicked.connect(rgeViews.newActor)

        self.addItem(self.nameLabel,0,0)
        self.addItem(self.nameDisplay,0,1)
        self.addItem(self.nameBox,1,1)
        self.addItem(self.saveButton,2,0)
        self.addItem(self.loadButton,2,1)
        self.addItem(self.newButton,3,0)


    def nameChanged(self):
        self.nameDisplay.setText(self.nameBox.text())
        rgeViews.setActorName(self.nameBox.text())

class actorSpritesTab(genericTab):
    ''' general settings for this'''

    def __init__(self, mainWindow, Settings):
        super(actorSpritesTab, self).__init__(mainWindow)
        self.widgetName = ACTOR_SPRITES_TAB
        self.widgetTitle = "Sprites"
        self.setToolTip(self.tr("Sprite settings."))
        self.setWindowTitle(self.tr("General Settings"))

        self.spritesList = QtGui.QComboBox()
        self.addSpriteButton = QtGui.QPushButton("Add Sprite")
        self.removeSpriteButton = QtGui.QPushButton("Remove Sprite")
        self.hideLabel = QtGui.QLabel("Hide sprite: ")
        self.hideCheckbox = QtGui.QCheckBox()
        self.sizeXLabel = QtGui.QLabel("Actor Size X: ")
        self.sizeX = QtGui.QDoubleSpinBox()
        self.sizeX.setDecimals(4)
        self.sizeX.setRange(.0001,10000)
        self.sizeYLabel = QtGui.QLabel("Actor Size Y: ")
        self.sizeY = QtGui.QDoubleSpinBox()
        self.sizeY.setDecimals(4)
        self.sizeY.setRange(.0001,10000)

        self.connectStuff()
        self.addSpriteButton.clicked.connect(rgeViews.actorAddSprite)
        self.removeSpriteButton.clicked.connect(rgeViews.actorRemoveSprite)

        self.updateMenu(Settings)

        self.addItem(self.spritesList,0,0)
        self.addItem(self.addSpriteButton,1,0)
        self.addItem(self.removeSpriteButton,1,1)
        self.addItem(self.hideLabel,2,0)
        self.addItem(self.hideCheckbox,2,1)
        self.addItem(self.sizeXLabel,3,0)
        self.addItem(self.sizeX,3,1)
        self.addItem(self.sizeYLabel,4,0)
        self.addItem(self.sizeY,4,1)


    def updateMenu(self, Settings):
        self.disconnectStuff()
        currentIndex = rgeViews.getCurrentLayer()
        if Settings.getNumOfSprites() <= currentIndex:
            currentIndex = Settings.getNumOfSprites() - 1
            if currentIndex < 0:
                currentIndex = 0
        self.spritesList.clear()
        for i in range(Settings.getNumOfSprites()):
            self.spritesList.addItem(Settings.getSpriteName(i))
        self.spritesList.setCurrentIndex(currentIndex)
        if Settings.getNumOfSprites() > 0:
            self.hideCheckbox.setChecked(Settings.getHide(currentIndex))
        self.sizeX.setValue(Settings.getSizeX())
        self.sizeY.setValue(Settings.getSizeY())
        self.connectStuff()
        return currentIndex


    def connectStuff(self):
        self.spritesList.currentIndexChanged.connect(rgeViews.actorSpriteIndexChanged)
        self.hideCheckbox.toggled.connect(self.hideFlipped)
        self.sizeX.valueChanged.connect(rgeViews.actorSizeXChanged)
        self.sizeY.valueChanged.connect(rgeViews.actorSizeYChanged)

    def disconnectStuff(self):
        self.spritesList.currentIndexChanged.disconnect(rgeViews.actorSpriteIndexChanged)
        self.hideCheckbox.toggled.disconnect(self.hideFlipped)
        self.sizeX.valueChanged.disconnect(rgeViews.actorSizeXChanged)
        self.sizeY.valueChanged.disconnect(rgeViews.actorSizeYChanged)

    def hideFlipped(self):
        rgeViews.actorHideChanged(self.hideCheckbox.isChecked())



class Sidebar(QtGui.QDockWidget):

    def __init__(self, mainWindow):
        """Initializes the pog palette."""
        super(QtGui.QDockWidget, self).__init__(mainWindow)
        self.setToolTip(self.tr("Editor tools."))
        self.setFeatures(QtGui.QDockWidget.DockWidgetFeatures(0))
        self.setWindowTitle(self.tr("Editing Tools"))
        self.widget = QtGui.QTabWidget(mainWindow)
        self.setWidget(self.widget)
        self.setObjectName("Editing Tools")

        self.widgets = {}
        self.widgetIndexes = {}

        self.widget.currentChanged.connect(rgeViews.TabChanged)

        mainWindow.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self)

    def addTab(self, NewTab):
        if NewTab.widgetName in self.widgets:
            return
        self.widgets[NewTab.widgetName] = NewTab
        self.widgetIndexes[NewTab.widgetName] = self.widget.addTab(self.widgets[NewTab.widgetName], NewTab.widgetTitle)

    def clearWidgetReferences(self, OldTabName):
        try:
            del self.widgets[OldTabName]
            del self.widgetIndexes[OldTabName]
        except KeyError as e:
            print "Error: attempted to clear references for nonexistent widget: " + str(OldTabName)

    def removeTab(self, OldTabName):
        if OldTabName in self.widgets:
            self.widget.removeTab(self.widgetIndexes[OldTabName])

    def clearTabs(self):
        self.widget.clear()
        for i in self.widgets.keys()[:]:
            self.clearWidgetReferences(i)
